package com.example.rbacmanage.resolver.app;

import com.alibaba.druid.util.StringUtils;
import com.example.rbacmanage.annotation.CurrentUser;
import com.example.rbacmanage.entity.app.AppUser;
import com.example.rbacmanage.mapper.app.AppUserMapper;
import com.example.rbacmanage.util.JwtTokenUtil;
import com.example.rbacmanage.util.SpringUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


@Component
public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(CurrentUser.class) != null &&
                parameter.getParameterType().equals(Long.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("AuthorizationappUser");
        if (!StringUtils.isEmpty(token)){
            String userId = JwtTokenUtil.getUsernameFromToken(token);
            AppUserMapper blogAppUserMapper = SpringUtils.getBean("appUserMapper");
            AppUser byId = blogAppUserMapper.queryOneById(Long.valueOf(userId));
            if (byId == null){
                return null;
            }
            return byId.getId();
        }
        return null;
    }
}
